package cn.house.houseai.service.impl;

import cn.house.houseai.entify.ChangePasswordRequest;
import cn.house.houseai.entify.Users;
import cn.house.houseai.properties.JwtProperties;
import cn.house.houseai.service.UserService;
import cn.house.houseai.tools.JwtUtil;
import cn.house.houseai.vo.ResultVo;
import cn.house.houseai.mapper.UserMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author 羡y
 * @date 2024/9/27
 * @Description
 */
@Service
@Slf4j
public class UserServiceImpl implements UserService {
    @Autowired
    private UserMapper userMapper;

    @Autowired
    private JwtProperties jwtProperties;

    private final BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();

    @Override
    public ResultVo queryAll() {
        List<Users> users = userMapper.queryAll();
        if (users == null || users.isEmpty()) {
            return new ResultVo(101, null, "没有找到用户");
        }
        return new ResultVo(100, users, "查询成功");
    }

    @Override
    public ResultVo login(String username, String password) {
        log.info("用户登录：{}", username);
        Users user = userMapper.getById(username);

        if (user == null) {
            return new ResultVo(101, null, "登录失败：用户不存在");
        }

        // 验证密码
        if (!passwordEncoder.matches(password, user.getPassword())) {
            return new ResultVo(101, null, "登录失败：密码错误");
        }

        // 生成 Token
        Map<String, Object> claims = new HashMap<>();
        claims.put("user_id", user.getUser_id());
        String token = JwtUtil.createJWT(jwtProperties.getUserSecretKey(), jwtProperties.getUserTtl(), claims);

        Map<String, Object> response = new HashMap<>();
        response.put("user_id", user.getUser_id());
        response.put("name", user.getUsername());
        response.put("token", token);

        return new ResultVo(100, response, "登录成功");
    }

    @Override
    public ResultVo register(Users user) {
        if (userMapper.getById(user.getUsername()) != null) {
            return new ResultVo(102, null, "用户名已存在，无法注册");
        }

        user.setPassword(hashPassword(user.getPassword()));

        try {
            userMapper.insertUser(user);
            return new ResultVo(100, user, "注册成功");
        } catch (Exception e) {
            log.error("注册失败", e);
            return new ResultVo(101, null, "注册失败: " + e.getMessage());
        }
    }

    @Override
    public ResultVo updateUser(int user_id, Users user) {
        user.setUser_id(user_id);
        int result = userMapper.updateUser(user);
        return result > 0 ? new ResultVo(100, user, "用户更新成功") : new ResultVo(101, null, "用户更新失败");
    }

    @Override
    public Users getById(String username) {
        return userMapper.getById(username);
    }

    @Override
    public ResultVo getByMessage(Integer user_id) {
        Users user = userMapper.selectUserId(user_id);
        return user != null ? new ResultVo(100, user, "查询成功") : new ResultVo(101, null, "查询失败");
    }

    @Override
    public ResultVo updatePassword(int user_id, ChangePasswordRequest request) {
        Users user = userMapper.getByPassword(user_id);
        if (user == null) {
            return new ResultVo(101, null, "用户不存在");
        }

        // 验证当前密码
        if (!passwordEncoder.matches(request.getCurrentPassword(), user.getPassword())) {
            return new ResultVo(101, null, "当前密码不正确");
        }

        // 更新新密码
        String newPasswordHash = passwordEncoder.encode(request.getNewPassword());
        userMapper.updatePassword(user_id, newPasswordHash);
        return new ResultVo(100, user, "密码修改成功");
    }

    private String hashPassword(String password) {
        return passwordEncoder.encode(password);
    }
}
